#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<sys/wait.h>
#include<sys/types.h>
int main()
{
  int fd[2]={0};
  if(pipe(fd)<0)
  {
    perror("pipe");
    return 1;
  }
  pid_t id=fork();
  if(id==0)
  {
    //child进程
    close(fd[0]);//子进程写
    const char* s="child";
    int count=100;
    while(count--)
    {
      write(fd[1],s,strlen(s));
      sleep(2);
    }
    close(fd[1]);
    exit(0);
  }
  //father
  close(fd[1]);//父进程读
  char rd[100];
  while(1)
  {
    ssize_t n=read(fd[0],rd,sizeof(rd));
    if(n>0)
    {
        rd[n]='\0';
        printf("father receive:%s\n",rd);
    }
    else if(n==0)
    {
      printf("read file end!\n");
      break;
    }
    else 
    {
      printf("read error\n");
      break;
    }
  }
  waitpid(id,NULL,0);//以阻塞的形式等待子进程
  return 0;
}
